/**
 * API 调用处理 Mixin
 * 提供统一的API调用、错误处理和消息提示
 */

export default {
  methods: {
    /**
     * 通用API调用处理
     * @param {Function} apiMethod - API方法
     * @param {any} params - 参数
     * @param {object} options - 配置选项
     * @returns {Promise<any>}
     */
    async handleApiCall(apiMethod, params = null, options = {}) {
      const {
        successMessage = '操作成功',
        errorMessage = '操作失败',
        showSuccess = true,
        showError = true,
        onSuccess = null,
        onError = null,
        loadingTarget = null,
        loadingProperty = 'loading',
        expectedStatus = [200, 201, 204]
      } = options;

      // 设置加载状态
      if (loadingTarget && loadingProperty) {
        this.$set(loadingTarget, loadingProperty, true);
      }

      try {
        const response = await apiMethod(params);
        
        if (expectedStatus.includes(response.status)) {
          // 成功处理
          if (showSuccess) {
            this.$message({
              type: 'success',
              message: successMessage,
              duration: 1500
            });
          }
          
          // 执行成功回调
          if (onSuccess && typeof onSuccess === 'function') {
            await onSuccess(response.data, response);
          }
          
          return response;
        } else {
          throw new Error(`意外的响应状态: ${response.status}`);
        }
      } catch (error) {
        console.error('API调用错误:', error);
        
        // 错误处理
        if (showError) {
          this.$message({
            type: 'error',
            message: error.response?.data?.message || error.message || errorMessage,
            duration: 2000
          });
        }
        
        // 执行错误回调
        if (onError && typeof onError === 'function') {
          await onError(error);
        }
        
        throw error;
      } finally {
        // 清除加载状态
        if (loadingTarget && loadingProperty) {
          this.$set(loadingTarget, loadingProperty, false);
        }
      }
    },

    /**
     * 处理CRUD操作
     * @param {string} operation - 操作类型 (create/update/delete)
     * @param {Function} apiMethod - API方法
     * @param {any} params - 参数
     * @param {object} options - 配置选项
     */
    async handleCrudOperation(operation, apiMethod, params, options = {}) {
      const operationConfig = {
        create: {
          successMessage: '创建成功',
          expectedStatus: [201]
        },
        update: {
          successMessage: '更新成功',
          expectedStatus: [200]
        },
        delete: {
          successMessage: '删除成功',
          expectedStatus: [204]
        }
      };

      const config = { ...operationConfig[operation], ...options };
      
      return await this.handleApiCall(apiMethod, params, config);
    },

    /**
     * 处理列表数据获取
     * @param {Function} apiMethod - API方法
     * @param {any} params - 参数
     * @param {string} dataProperty - 存储数据的属性名
     * @param {object} options - 配置选项
     */
    async handleFetchList(apiMethod, params, dataProperty = 'list', options = {}) {
      const defaultOptions = {
        showSuccess: false,
        onSuccess: (data) => {
          if (Array.isArray(data)) {
            this[dataProperty] = data;
          } else if (data && Array.isArray(data.result)) {
            this[dataProperty] = data.result;
            // 处理分页信息
            if (data.count !== undefined && this.pages) {
              this.pages.count = data.count;
            }
          } else {
            console.warn('API返回的数据格式不符合预期:', data);
          }
        },
        ...options
      };

      return await this.handleApiCall(apiMethod, params, defaultOptions);
    },

    /**
     * 处理详情数据获取
     * @param {Function} apiMethod - API方法
     * @param {any} params - 参数
     * @param {string} dataProperty - 存储数据的属性名
     * @param {object} options - 配置选项
     */
    async handleFetchDetail(apiMethod, params, dataProperty = 'detail', options = {}) {
      const defaultOptions = {
        showSuccess: false,
        onSuccess: (data) => {
          this[dataProperty] = data;
        },
        ...options
      };

      return await this.handleApiCall(apiMethod, params, defaultOptions);
    },

    /**
     * 带确认的删除操作
     * @param {Function} apiMethod - API方法
     * @param {any} params - 参数
     * @param {object} options - 配置选项
     */
    async handleConfirmDelete(apiMethod, params, options = {}) {
      const {
        title = '提示',
        message = '此操作将永久删除该数据, 是否继续?',
        confirmButtonText = '确定',
        cancelButtonText = '取消',
        onSuccess = null,
        ...apiOptions
      } = options;

      try {
        await this.$confirm(message, title, {
          confirmButtonText,
          cancelButtonText,
          type: 'warning'
        });

        return await this.handleCrudOperation('delete', apiMethod, params, {
          onSuccess: async (data, response) => {
            if (onSuccess && typeof onSuccess === 'function') {
              await onSuccess(data, response);
            }
          },
          ...apiOptions
        });
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 1000
          });
        }
        throw error;
      }
    },

    /**
     * 批量操作处理
     * @param {Function} apiMethod - API方法
     * @param {Array} items - 要处理的项目列表
     * @param {object} options - 配置选项
     */
    async handleBatchOperation(apiMethod, items, options = {}) {
      const {
        batchSize = 10,
        successMessage = '批量操作完成',
        onProgress = null,
        ...apiOptions
      } = options;

      if (!Array.isArray(items) || items.length === 0) {
        throw new Error('没有要处理的项目');
      }

      const results = [];
      const totalItems = items.length;
      
      for (let i = 0; i < totalItems; i += batchSize) {
        const batch = items.slice(i, i + batchSize);
        
        try {
          const response = await this.handleApiCall(apiMethod, batch, {
            showSuccess: false,
            ...apiOptions
          });
          results.push(response);
          
          // 进度回调
          if (onProgress && typeof onProgress === 'function') {
            onProgress({
              processed: Math.min(i + batchSize, totalItems),
              total: totalItems,
              progress: Math.min((i + batchSize) / totalItems * 100, 100)
            });
          }
        } catch (error) {
          console.error(`批量操作第 ${Math.floor(i / batchSize) + 1} 批失败:`, error);
          throw error;
        }
      }

      this.$message({
        type: 'success',
        message: successMessage,
        duration: 1500
      });

      return results;
    }
  }
};